import 'package:flutter/material.dart';
import '../../application.dart';
import '../../utils/tools.dart';
import '../../widgets/tags/divider.dart';
import '../../widgets/tags/empty.dart';
import '../../utils/api.dart';
import '../../models/article_model.dart';
import '../../models/category_model.dart';
import '../../models/search_arguments.dart';

class ListPage extends StatefulWidget {
  final SearchArguments arguments;

  const ListPage({Key key, this.arguments}) : super(key: key);

  @override
  _ListPageState createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> with SingleTickerProviderStateMixin {
  String _title = "文章";

  int topId = 0;
  int cateId = 0;

  int page = 1;
  int pageSize = 10;
  int total = 0;

  List<CategoryModel> _cates;
  List<ArticleModel> _list;
  bool isLoading = true;
  bool isInitialize = false;
  bool hasMore = true;

  ScrollController _scrollController;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    var arguments = widget.arguments;
    if (arguments.category != null) {
      this.cateId = arguments.category;
    }
    if (arguments.topCategory != null && arguments.topCategory > 0) {
      this.topId = arguments.topCategory;
    }else{
      this.topId = this.cateId;
    }
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);

    _list = List();
    _loadCategory();
  }

  _onScroll() {
    if (!isLoading) {
      //print(_scrollController.position);
      if (hasMore &&
          _scrollController.position.pixels + 10 >=
              _scrollController.position.maxScrollExtent) {
        setState(() {
          isLoading = true;
        });
        page++;
        _loadData();
      }
    }
  }

  _changeCate(int cateId) {
    setState(() {
      this.cateId = cateId;
    });
    _reloadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
      ),
      body: isInitialize
          ? Column(
              children: <Widget>[
                (_cates == null || _cates.isEmpty)
                    ? SizedBox()
                    : TabBar(
                        onTap: (idx) {
                          cateId = _cates[idx].id;
                          _changeCate(cateId);
                        },
                        isScrollable: true,
                        labelColor: Colors.blue,
                        unselectedLabelColor: Colors.black54,
                        labelStyle: TextStyle(fontSize: 16),
                        controller: _tabController,
                        tabs: _cates.map<Tab>((item) {
                          return Tab(
                            text: item.title,
                          );
                        }).toList(),
                      ),
                _renderList(),
              ],
            )
          : Center(
              child: CircularProgressIndicator(),
            ),
    );
  }

  _renderList() {
    if (_list == null || _list.isEmpty) {
      if (isLoading) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return TagEmpty('该类目暂无文章');
    }

    List<Widget> childs = _list.map<Widget>((art) {
      return Card(
        child: ListTile(
          onTap: (){
            Application.route('/article/detail',arguments:{ 'id':art.id ,'data':art});
          },
          leading:(art.cover != null && art.cover.isNotEmpty)?Tools.image(art.cover,width:80,height:60):null,
          title: Text(art.title),
          subtitle: Text(art.description, maxLines: 3,),
        ),
      );
    }).toList();

    if (isLoading) {
      childs.add(Padding(
        padding: EdgeInsets.symmetric(vertical: 10),
        child: Center(
          child: SizedBox(
            height: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2,
            ),
          ),
        ),
      ));
    } else if (!hasMore) {
      childs.add(TagDivider('没有更多了~'));
    }

    return Expanded(
      child: ListView(
        controller: _scrollController,
        children: childs,
      ),
    );
  }

  _loadCategory() async {
    Api.post('article/get_cates', {'pid': this.topId}).then((result) {
      var list = result.list;
      if (list != null) {
        setState(() {
          _cates = list.map<CategoryModel>((item) => CategoryModel.fromJson(item)).toList();
          int initIndex= 0;
          if(cateId == 0 || cateId==topId) {
            this.cateId = _cates[0].id;
          }else{
            initIndex = _cates.indexWhere( (item)=>item.id == cateId);
            if(initIndex < 0){
              initIndex = 0;
              cateId = _cates[0].id;
            }
          }
          _tabController = TabController( initialIndex:(initIndex<=0?0:initIndex),length:_cates.length, vsync: this);
          
        });
      } else {
        this.cateId = this.topId;
      }
      setState(() {
        isInitialize = true;
      });
      _loadData();
    });
  }

  _reloadData() {
    setState(() {
      page = 1;
      hasMore = true;
      isLoading = true;
      _list.clear();
    });
    _loadData();
  }

  _loadData() async {
    Api.post('article/get_list', {
      'cate': this.cateId,
      'page': this.page,
      'pagesize': this.pageSize
    }).then((result) {
      if (!mounted) return;
      var lists = result.data['lists'];
      //print(lists);
      setState(() {
        isLoading = false;
        total = Tools.parseInt(result.data['total']);
        if (lists != null) {
          _list += lists.map<ArticleModel>((item) => ArticleModel.fromJson(item)).toList();
        }
        if (lists == null || lists.length < pageSize || _list.length >= total) {
          hasMore = false;
        }
      });
    }).catchError((err) {
      setState(() {
        isLoading = false;
      });
    });
  }
}
